from datetime import datetime

from django.contrib import auth
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from application.models import User, Org
from django.core import serializers
from virtapp.utils.model_utils import to_json, to_page
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.sessions.models import Session
import random, json, cv2, string,  numpy as np



def getImg(request: WSGIRequest):
    """
        认证码
    """
    width=130
    height=50
    chars=string.ascii_uppercase + string.ascii_lowercase + string.digits
    count=4
    # 生成随机验证码
    captcha_text = ''.join([random.choice(chars) for _ in range(count)])
    request.session['checkCode'] = captcha_text.lower()
    print(captcha_text.lower())
    request.session.save()
    # 创建空白图像
    image = np.zeros((height, width, 3), np.uint8)
    image.fill(255)  # 使用白色背景
    # 设置文本属性
    font_face = cv2.FONT_HERSHEY_SIMPLEX
    font_scale = 1
    color = (20, 80, 0)
    thickness = 1
    p = random.randint(5,20)
    for i in captcha_text:
        # 在图像上绘制文本
        cv2.putText(image, i, (p, height//2 + 10), font_face, font_scale, color, 2)
        n = random.randint(20,30)
        p+=n

    # 添加噪声
    for i in range(30):
        x1= random.randint(0, 150) % 200
        y1= random.randint(0, 50) 
        x= random.randint(-1,1) 
        y= random.randint(-1,1) 
        cv2.line(image, (x1, y1), (x1+x, y1+y), color, 1)

    for i in range(8):
        x1= random.randint(0, 150) % 200
        y1= random.randint(0, 50) 
        x= random.randint(-15,15) 
        y= random.randint(-15,15) 
        cv2.line(image, (x1, y1), (x1+x, y1+y), color, 2)

    _, img = cv2.imencode('.png', image)
    return HttpResponse(img.tobytes(), content_type='image/png')

def login(request: WSGIRequest):
    """
        登录页
    """
    if(isinstance(request.user, User)):
        return HttpResponse(json.dumps({"status": "success"}), content_type="application/json") 
    if request.method == 'POST':
        username = request.POST.get("username")
        password = request.POST.get("password")
        checkCode = request.POST.get("checkCode")
        if(checkCode is None or checkCode.lower() != request.session.get('checkCode')):
             return HttpResponse(json.dumps({"status": "fail", "msg": "认证码错误"}), content_type="application/json")
        user = User.objects.filter(username=username).first()
        if user:
            if user.check_password(password):
                auth.login(request=request, user=user)
                return HttpResponse(json.dumps({"status": "success"}), content_type="application/json")
            else:
                return HttpResponse(json.dumps({"status": "fail","msg": "用户或密码错误"}), content_type="application/json")
        return HttpResponse(json.dumps({"status": "fail","msg": "用户或密码错误"}), content_type="application/json")
    return render(request, "login.html", locals())

def logout(request: WSGIRequest):
    """
    退出登录
    """
    auth.logout(request=request)
    return redirect("/login")

def get_logins(request: WSGIRequest):
    page_number = request.GET.get("page_index", 1)
    page_size = request.GET.get("page_size", 10)
    sessions = Session.objects.filter(expire_date__gte=datetime.now())
    user_ids = []
    for session in sessions:
        session_info = session.get_decoded()
        if session_info.get('_auth_user_id'):
            user_ids.append(session_info['_auth_user_id'])
    return HttpResponse(to_json(to_page(User.objects.filter(id__in=user_ids),page_number, page_size=page_size), "password"), content_type="application/json")

def index(request: WSGIRequest):
    return render(request,"index.html", locals())

def userAdd(request: WSGIRequest):
    
    return render(request,"index.html", locals())

def delUser(request: WSGIRequest):
    user_id = request.GET['id']
    user = User.objects.filter(id=user_id)
    if user.delete()[0] == 1:
        return HttpResponse("ok", content_type="application/json")
    return HttpResponse("fail", content_type="application/json")

def users(request: WSGIRequest):
    return HttpResponse(serializers.serialize("json", User.objects.exclude(username="admin").all()), content_type="application/json")

def android(request: WSGIRequest):
    return HttpResponse("ok", content_type="application/json")

def get_org(request: WSGIRequest):
    
    return HttpResponse(to_json(Org.objects.all(),"group_ptr_id"), content_type="application/json")
